<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-11-28 14:15
 *
 * Version: 2.0
 */

namespace App\Modules\RedBag\Repositories;


use App\Exceptions\NotFoundException;
use App\Models\RedBag;
use Flower\Core\Repository\Eloquent\BaseRepository;

class RedBagRepository extends BaseRepository
{
	public function model()
	{
		return RedBag::class;
	}

	/**
	 * 检测红包是否存在
	 * @param $id
	 * @return mixed
	 * @throws NotFoundException
	 */
	public function isExited($id)
	{
		$Info = $this->find($id);
		if (empty($Info)) {
			throw new NotFoundException(['msg' => '红包不存在！']);
		}
		return $Info;
	}

	public function addItem($params, $userId)
	{
		$data = [
			'store_id'        => $params['store_id'],
			'user_id'         => $userId,
			'send_start_time' => date('Y-m-d H:i:s'),
			'send_end_time'   => date('Y-m-d H:i:s', strtotime('+1 hour')),
			'money'           => $params['money'],
			'create_num'      => $params['create_num'],
			'back_num'        => 0,
			'status'          => 1,
			'created_at'      => date('Y-m-d H:i:s'),
			'live_id'         => $params['live_id']
		];
		return $this->model->insertGetId($data);
	}

	public function checkHasRedBag($userId,$storeId){
		return $this->model->select(['id','money','create_num','send_num','created_at'])->where(['user_id'=>$userId,'store_id'=>$storeId,'status'=>1])->where('created_at','>=',date('Y-m-d H:i:s',time()-config('constant.check_live_is_send_gift_time')))->orderBy('id','desc')->first();
	}

	/**
	 * 获取未领完的红包
	 * @param $userId
	 * @param $storeId
	 * @return mixed
	 */
	public function getRedBagList($userId,$storeId){
		return $this->model->where(['user_id'=>$userId,'store_id'=>$storeId])->where('create_num','!=','send_num')->get();
	}
}